<?php
namespace data\service;

use data\model\User;
use think\facade\Session;

class UserService extends BaseService{

    // 模型初始化
    public function __construct()
    {
        $this->model = new User;
    }

    /**
     * 判断用户是否存在
     * @desc
     * @param $openid
     * @return mixed
     * @author 16
     * @date 2018/3/15
     */
    public function isExists($openid)
    {
        return $this->model->where('openid','=',$openid)->value('id');
    }

    /**
     * 检查用户信息是否正确
     * @desc
     * @param $post
     * @return array|bool|null|\PDOStatement|string|\think\Model
     * @author 16
     * @date 2018/2/24
     */
    public function checkUser($post)
    {
        if(!$user = $this->model->getUserByUsername($post['account'],'id,account,password,iden,nickname')){
            $this->errMsg = '用户不存在';
        } elseif ($user->iden != User::IDEN_ADMIN){
            $this->errMsg = '用户没有权限登陆';
        } elseif (md5($post['psw']) != $user->password) {
            $this->errMsg = '密码错误!';
        } else {
            return $user;
        }

        return false;
    }

    /**
     * 存储登陆信息
     * @author 16
     * @date 2018-2-24
     */
    public function setLoginStatus($user)
    {
        Session::set('adminUser',$user);
        Session::set('prevLoginInfo',cache('login_'.$user->account));  //获取上次登录的信息

        $loginInfo = [
            'login_time' => time(),
            'login_address' => getUserAddressByIp(),
            'ip'=>request()->ip()
        ];

        cache('login_'.$user->account,$loginInfo);    //存储本次登录的信息
    }

    /**
     * 获取用户总数
     * @desc
     * @author 16
     * @date 2018/3/20
     */
    public function getUserCount()
    {
        return User::count();
    }

    /**
     * 当天关注总数
     * @desc
     * @author 16
     * @date 2018/3/20
     */
    public function getTodayFollowCount()
    {
        return User::where('create_at','>',strtotime(date('Y-m-d',time())))->count();
    }

}